package com.atguigu.ssyx.home.service.impl;

import com.atguigu.ssyx.activity.client.ActivityFeignClient;
import com.atguigu.ssyx.client.product.ProductFeignClient;
import com.atguigu.ssyx.home.service.ItemService;
import com.atguigu.ssyx.search.SkuFeignClient;
import com.atguigu.ssyx.vo.product.SkuInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;


/**
 * Created with IntelliJ IDEA.
 * ClassName: ItemServiceImpl
 * Package: com.atguigu.ssyx.home.service.impl
 * Description:
 * User: fzykd
 *
 * @Author: LQH
 * Date: 2023-10-04
 * Time: 14:18
 */

@Service
public class ItemServiceImpl implements ItemService {

    //自定义线程池
    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Autowired
    private ProductFeignClient productFeignClient;

    @Autowired
    private ActivityFeignClient activityFeignClient;

    @Autowired
    private SkuFeignClient skuFeignClient;

    //sku商品的详情信息
    //实现技术 远程调用 + 多线程
    @Override
    public Map<String, Object> item(Long skuId, Long userId) {
        //远程调用可以实现 但是现有新的实现方式 多线程方式实现
        Map<String, Object> map = new HashMap<>();

        //skuId查询
        //supplyAsync 创建异步对象 支持返回值
        CompletableFuture<SkuInfoVo> skuInfoVoFuture = CompletableFuture.supplyAsync(() -> {
            //远程调用获取sku对应的数据  在service-product中
            SkuInfoVo skuInfoVo = productFeignClient.getSkuInfoVo(skuId);
            map.put("skuInfoVo", skuInfoVo);
            return skuInfoVo;
        }, threadPoolExecutor);
        //还有一个参数 是自定义线程池 如果不添加参数 那么就是默认的一个线程池

        //远程调用 sku优惠卷信息
        //runAsync 不需要返回值
        CompletableFuture<Void> activityFuture = CompletableFuture.runAsync(() -> {
            //远程调用获取优惠卷信息 service-activity
            Map<String, Object> activityMap = activityFeignClient.findActivityAndCoupon(skuId, userId);

            map.putAll(activityMap);
        }, threadPoolExecutor);

        //更新商品的热度
        CompletableFuture<Void> hotFuture = CompletableFuture.runAsync(() -> {
            //远程调用更新热度
            skuFeignClient.incrHotScore(skuId);

        }, threadPoolExecutor);

        //三个任务都执行完 往后在执行 就是一个任务的组合
        CompletableFuture.allOf(
                skuInfoVoFuture,
                activityFuture,
                hotFuture
        ).join();

        return map;
    }


}
